<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="css/mui.css" rel="stylesheet" />
	</head>

	<body style="background-color: #666;">

		<canvas id="my_face_canvas"></canvas>
		<canvas id="my_face_canvas_hidden" style="display: none;"></canvas>
		<button id="submit" style="position: absolute; left: 20px; bottom: 20px; ">确定</button>
		<script src="js/mui.js"></script>
		<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			mui.init();
			
			var cw = document.documentElement.clientWidth;
			var ch = document.documentElement.clientHeight;
			
			function getDistance(p1, p2) {
				var x = parseInt(p2.pageX) - parseInt(p1.pageX),
					y = parseInt(p2.pageY) - parseInt(p1.pageY);
				return Math.sqrt((x * x) + (y * y));
			}
			
			function refresh(ctx, myImg, xOffset, yOffset, currentScale) {
				var ratio = (myImg.width > myImg.height)
						  ? (cw - 40) / myImg.height
						  : (cw - 40) / myImg.width;
				
				var ix = 0, iy = 0, iw = 0, ih = 0;
				var sx = 0, sy = 0, sw = 0, sh = 0;
				var sxStart = (cw / 2 - (myImg.width / 2 - xOffset) * ratio * currentScale);
				var syStart = (ch / 2 - (myImg.height / 2 - yOffset) * ratio * currentScale);
				var sxEnd = (cw / 2 + (myImg.width / 2 - xOffset) * ratio * currentScale);
				var syEnd = (ch / 2 + (myImg.height / 2 - yOffset) * ratio * currentScale);
				
				if (sxStart < 0) {
					sx = 0;
					ix = -sxStart / ratio / currentScale;
					sw = Math.max(cw, sxEnd);
					iw = sw / ratio / currentScale;
				} else {
					sx = sxStart;
					ix = 0;
					sw = Math.max(cw, sxEnd) - sxStart;
					iw = sw / ratio / currentScale;
				}
				
				if (syStart < 0) {
					sy = 0;
					iy = -syStart / ratio / currentScale;
					sh = Math.max(ch, syEnd);
					ih = sh / ratio / currentScale;
				} else {
					sy = syStart;
					iy = 0;
					sh = Math.max(ch, syEnd) - syStart;
					ih = sh / ratio / currentScale;
				}
				
				ctx.clearRect(0, 0, cw, ch);
				ctx.drawImage(myImg, ix, iy, iw, ih, sx, sy, sw, sh);
			}
			
			function refreshBorder(ctx, h) {
				ctx.fillStyle = "rgba(0, 0, 0, 0.6)";
				ctx.fillRect(0, 0, cw, h);
				ctx.fillRect(0, ch - h, cw, h);
				ctx.fillRect(0, h, 20, ch - 2 * h);
				ctx.fillRect(cw - 20, h, 20, ch - 2 * h);
			}

			mui.plusReady(function() {
				var my_face_canvas = document.getElementById("my_face_canvas");
				var my_face_canvas_hidden = document.getElementById("my_face_canvas_hidden");

				var myImg = new Image;
				myImg.src = plus.webview.currentWebview().face_path;

				my_face_canvas.width = cw;
				my_face_canvas.height = ch;

				my_face_canvas_hidden.width = cw - 40;
				my_face_canvas_hidden.height = cw - 40;

				var h = parseInt((ch - cw) / 2) + 20;
				var ctx = my_face_canvas.getContext("2d");
				var canvas = my_face_canvas_hidden.getContext("2d");
				
				var start = [];
				var previousTouch = null;
				var xOffset = 0, yOffset = 0;
				var scale = 1.0, currentScale = 1.0;
				var touchMode = 0;

				myImg.onload = function() {
					refresh(ctx, myImg, xOffset, yOffset, currentScale);
					refreshBorder(ctx, h);
				}

				my_face_canvas.addEventListener("touchstart", function(e) {
					if (e.touches.length == 1) {
						previousTouch = e.touches[0];
					} else if (e.touches.length == 2) {
						start = e.touches;
						scale = currentScale;
					}
					touchMode = e.touches.length;
				}, false);
				document.addEventListener("touchmove", function(e) {
					e.preventDefault();
					var ratio = (myImg.width > myImg.height)
							  ? (cw - 40) / myImg.height
							  : (cw - 40) / myImg.width;
					if (e.touches.length == 1) {
						if (touchMode == 2) {
							previousTouch = e.touches[0];
						} else {
							var xDelta = parseInt(e.touches[0].pageX) - parseInt(previousTouch.pageX);
							var yDelta = parseInt(e.touches[0].pageY) - parseInt(previousTouch.pageY);
							
							xOffset = xOffset + xDelta / ratio / currentScale;
							yOffset = yOffset + yDelta / ratio / currentScale;
							
							previousTouch = e.touches[0];
						}
					} else if (e.touches.length == 2) {
						var tempScale = getDistance(e.touches[0], e.touches[1])
									  / getDistance(start[0], start[1]);
						if (tempScale * scale < 1) {
							return;
						}
						currentScale = tempScale * scale;
					}
					
					refresh(ctx, myImg, xOffset, yOffset, currentScale);
					refreshBorder(ctx, h);	
				});

				var submit = document.getElementById("submit");
				submit.addEventListener("tap", async function() {
					var filename = app.getGlobalUserInfo().id + ".jpg";
					// 获取头像上传地址
					var serverUrl = app.serverAddress +
						"/u/upload_file_path?filename=" +
						filename;
					const url = await fetch(serverUrl)
						.then(response => {
							return response.json();
						})
						.catch(err => console.log(err));

					canvas.putImageData(ctx.getImageData(20, h, cw - 40, cw - 40), 0, 0);
					var dataurl = my_face_canvas_hidden.toDataURL("image/jpg");
					plus.storage.setItem(app.getGlobalUserInfo().id.toString(), dataurl);
					
					var arr = dataurl.split(','),
						mime = arr[0].match(/:(.*?);/)[1],
						bstr = atob(arr[1]),
						n = bstr.length,
						u8arr = new Uint8Array(n);
					while (n--) {
						u8arr[n] = bstr.charCodeAt(n);
					}

					fetch(url.msg, {
							method: 'PUT',
							body: u8arr
						})
						.then(() => {
							// 头像上传图片服务器成功
							var data = {
								id: app.getGlobalUserInfo().id,
								facepath: 'http://192.168.1.7/chat/' + filename
							};
							fetch(app.serverAddress + '/u/update_facepath', {
									method: 'PUT',
									body: JSON.stringify(data),
									headers: {
										'content-type': 'application/json'
									}
								})
								.then(() => {
									plus.webview.getWebviewById("me.html").reload();
									mui.toast("头像上传成功");
								})
								.catch((error) => {
									console.error('Some error happened: ' + error);
								});
						})
						.catch(error => mui.toast("头像上传失败"));
				});
			});
		</script>
	</body>
</html>
